package com.cmcc.shared.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.util.DisplayMetrics;

import com.cmcc.shared.SdkManager;

import java.util.Locale;

/**
 * Author: jiangxin
 * Date: 2018/12/19
 * Description:
 */
public class LanguageUtil {


    public static Context setLocal(Context context, int language) {
        return updateResources(context, getSetLocale(language));
    }

    private static Context updateResources(Context context, Locale locale) {
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            config.setLocale(locale);
            context = context.createConfigurationContext(config);
        } else {
            config.locale = locale;
            res.updateConfiguration(config, res.getDisplayMetrics());
        }
        return context;
    }

    public static void setLocale(Context context, int language) {
        Locale targetLocale = getSetLocale(language);
        Resources resources = context.getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        config.locale = targetLocale;
        resources.updateConfiguration(config, dm);
    }

    public static Context attachBaseContext(Context context, int language) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 8.0需要使用createConfigurationContext处理
            return updateResources(context, language);
        } else {
            return context;
        }
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, int language) {
        Resources resources = context.getResources();
        Locale locale = getSetLocale(language);// getSetLocale方法是获取新设置的语言

        Configuration configuration = resources.getConfiguration();
        configuration.setLocale(locale);
        configuration.setLocales(new LocaleList(locale));
        return context.createConfigurationContext(configuration);
    }

    private static Locale getSetLocale(int language) {
        if (language == SdkManager.LANGUAGE_ZH_TW)
            return Locale.TRADITIONAL_CHINESE;
        else if (language == SdkManager.LANGUAGE_ZH_CN) {
            return Locale.SIMPLIFIED_CHINESE;
        } else if (language == SdkManager.LANGUAGE_ENG) {
            return Locale.ENGLISH;
        } else
            return Locale.TRADITIONAL_CHINESE;
    }

}
